<template>
  <div>
    <el-dialog
      :visible.sync="addUserVisible"
      title="添加用户"
      @close="closeAddUserDialog"
    >
      <el-form :model="roleUserData" ref="rolesForm" :rules="roleFormRules">
        <el-form-item label="用户名称" prop="roleName"
          ><el-input v-model="roleUserData.roleName"></el-input
        ></el-form-item>
        <el-form-item label="角色描述" prop="roleDesc"
          ><el-input v-model="roleUserData.roleDesc"></el-input
        ></el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="closeAddUserDialog">取消</el-button>
        <el-button type="primary" @click="addUser">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AddUserDialog',
  data() {
    return {
      // 添加用户表单绑定的数据
      roleUserData: {
        roleName: '',
        roleDesc: ''
      },
      // 表单验证规则
      roleFormRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入用户描述', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 控制表单显示与隐藏的计算属性
    addUserVisible: {
      get() {
        return this.$store.state.roles.addUserVisible
      },
      set() {
        this.$store.commit('roles/addUserVisibleState', false)
      }
    }
  },
  methods: {
    // 添加用户方法
    addUser() {
      this.$refs.rolesForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写表单！')
        const { data: res } = await this.$http.post('roles', this.roleUserData)
        if (res.meta.status !== 201) return this.$message.error('数据提交失败!')

        this.$message.success('数据提交成功!')
        this.closeAddUserDialog()

        this.$emit('updateList')
      })
    },
    // 关闭对话框方法
    closeAddUserDialog() {
      this.$refs.rolesForm.resetFields()
      this.$store.commit('roles/addUserVisibleState', false)
    }
  }
}
</script>

<style></style>
